from flask import  *
from flask import render_template
from flask_mqtt import Mqtt
from flask_cors import CORS
import cv2 
import numpy as np
app=Flask(__name__)
cors = CORS(app, resources={r"/*": {"/web": "*"}, })
#跨域

# 配置信息
app.config['MQTT_BROKER_URL'] = '49.234.216.229'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 60
app.config['MQTT_TLS_ENABLED'] = False
app.config['MQTT_LAST_WILL_TOPIC'] = 'home/lastwill'
app.config['MQTT_LAST_WILL_MESSAGE'] = 'bye'
app.config['MQTT_LAST_WILL_QOS'] = 2
# MQTT 客户端
mqtt_client = Mqtt(app)


i=0
@app.route('/',methods=['GET','POST'])
def index():
    global i
    # print(request.data)
    nparr = np.frombuffer(request.data, np.uint8)
    img = cv2.imdecode(nparr,1)

    cv2.imwrite("G:\\TJ\\IOTpreparation\\esp32ImageTrans\\statics\\img\\"+str(i)+".png",img)
    # 保存图片函数
    i+=1
    return "ok"   
@app.route('/web',methods=['GET','POST'])
def web():
    # 测试用的网页
    return render_template('index.html')
@app.route('/cmd',methods=['GET','POST'])
def cmd():
    #通信方式任意，最后写publish即可。
    # print(request.data)
    
    mqtt_client.publish("TakeAPicture","anymsg")
    return "ok" 
if __name__ == '__main__':
    app.run(app)